package com.ikingtech.datav.config;

import cn.hutool.core.collection.CollUtil;
import com.ikingtech.framework.sdk.context.security.Me;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * created on 2024-03-05 11:15
 *
 * @author wub
 */
@Slf4j
public class ResourceFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Me.info().setTenantCode("sys");

        if (MediaType.APPLICATION_JSON_VALUE.equals(request.getHeader("Content-Type"))) {
            String postContent = getBody(request);
            String filter = new RequestRouter().filter(postContent, getUri(request));
            request = new BodyRequestWrapper(request, filter);
        }

        // 重构响应参数
        BodyResponseWrapper responseWrapper = new BodyResponseWrapper(response);
        filterChain.doFilter(request, responseWrapper);
        byte[] content = responseWrapper.getContent();
        if (content.length > 0) {
            String str = new String(content, StandardCharsets.UTF_8);
            try {
                str = new ResponseRouter().filter(str, getUri(request));
            } catch (Exception e) {
                log.error("response router error", e);
            }
            //把返回值输出到客户端
            ServletOutputStream outputStream = response.getOutputStream();
            if (!str.isEmpty()) {
                outputStream.write(str.getBytes());
                outputStream.flush();
                outputStream.close();
                //最后添加这一句，输出到客户端
                response.flushBuffer();
            }
        }

    }

    public  String getUri(HttpServletRequest request){
        String uri = request.getRequestURI();
        List<String> list = CollUtil.newArrayList(uri.split( "/"));
        list.removeIf(StringUtils::isNumeric); //去掉url中的数字参数
        list.removeIf(c -> c.contains(","));// 去掉url中的逗号分隔参数
        return StringUtils.join(list, "/");
    }


    private String getBody(ServletRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

}
